<template>
  <div class="pagination">
    <!-- 左边 -->
    <button :disabled="pageNo === 1"  @click="$emit('getPageNo', pageNo - 1)">上一页</button>
    <button
      v-show="startPageAndendPage.startPage > 1"
      @click="$emit('getPageNo', 1)"
      :class="{active:pageNo === 1}"
    >
      1
    </button>
    <button v-show="startPageAndendPage.startPage > 2">...</button>

    <!-- 中间 -->
    <button
      v-for="(page, index) in startPageAndendPage.endPage"
      :key="index"
      v-show="page >= startPageAndendPage.startPage"
      @click="$emit('getPageNo',page)"
      :class="{active:pageNo === page}"
    >
      {{ page }}
    </button>

    <!-- 右边 -->
    <button v-show="startPageAndendPage.endPage < totalPage - 1">...</button>
    <button
      v-show="startPageAndendPage.endPage < totalPage"
      @click="$emit('getPageNo', totalPage)"
      :class="{active:pageNo === totalPage}"
    >
      {{ totalPage }}
    </button>
    <button @click="$emit('getPageNo',pageNo+1)">下一页</button>

    <button style="margin-left: 30px">共{{ total }}条</button><br />
    {{ startPageAndendPage }}
  </div>
</template>

<script>
export default {
  name: "Pagination",
  props: ["pageNo", "continuous", "pageSize", "total"], //接收页码数据
  computed: {
    totalPage() {
      const { pageSize, total } = this;
      return Math.ceil(total / pageSize);
    },

    startPageAndendPage() {
      const { pageNo, continuous, totalPage } = this; //解构赋值获取
      let startPage,
        endPage = 0; // 连续页码的起始页码和结束页码
      //不正常现象（连续页码大于总页数）
      if (continuous > totalPage) {
        startPage = 1; //起始页为1
        endPage = totalPage; //结束页为总页数
      } else {
        //正常情况（也分多种情况）
        startPage = pageNo - parseInt(continuous / 2);
        endPage = pageNo + parseInt(continuous / 2);
        //两种特殊情况: startPage<1  endPage>总页数
        if (startPage < 1) {
          startPage = 1;
          endPage = continuous;
        }
        if (endPage > totalPage) {
          startPage = totalPage - continuous + 1;
          endPage = totalPage;
        }
      }
      return { startPage, endPage };
    },
  },

  methods: {},
};
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #E1251B;
      color: #fff;
    }
  }
}
</style>